package com.github.baichuan.application.scaffold.jpa.authorization;

import com.github.baichuan.application.scaffold.domain.application.Application;
import com.github.baichuan.application.scaffold.domain.authorization.Role;
import com.github.baichuan.application.scaffold.domain.identity.ApplicationMember;
import jakarta.persistence.criteria.*;
import lombok.Builder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;

@Builder
public class RoleSpecification implements Specification<Role> {
    //角色名称
    private String keyword;
    private Application application;
    private ApplicationMember applicationMember;

    @Override
    public Predicate toPredicate(Root<Role> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder builder) {
        if (application == null) {
            throw new IllegalStateException("application is null");
        }
        if (applicationMember == null) {
            throw new IllegalStateException("memberUid is null");
        }

        Predicate restrictions = builder.equal(root.get("application"), application);

        if (!applicationMember.isAdmin()) {
            restrictions = builder.and(restrictions, builder.equal(root.get("tenant"), applicationMember.getOrg().getTenant()));
        }

        if (StringUtils.isNotBlank(keyword)) {
            String value = "%" + keyword.trim() + "%";
            Predicate nameLike = builder.like(root.get("name"), value);
            restrictions = builder.and(restrictions, nameLike);
        }
        return restrictions;
    }
}
